package org.wk.core.db.dao.lang.covert;

import java.lang.reflect.Type;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.google.gson.JsonDeserializationContext;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonParseException;

/**
 *  
 * @ClassName	: StringToDateInJson
 * @Package		：org.wk.core.db.dao.lang.covert
 * @Author df.w 
 * @Create Time	：2018年5月2日 上午9:55:06
 * @Description	:
 */
public class StringToDateInJson implements JsonDeserializer<Date> {
	@Override
	public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context)
			throws JsonParseException {
		Map<String, String> patternMap = new HashMap<String, String>();
		patternMap.put("[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{4}Z",
				"yyyy-MM-dd'T'HH:mm:ss.SSSZ'Z'");
		patternMap.put("[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}\\.[0-9]{3}Z",
				"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
		patternMap.put("[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z", "yyyy-MM-dd'T'HH:mm:ss'Z'");
		patternMap.put("[0-9]{4}-[0-9]{2}-[0-9]{2}", "yyyy-MM-dd");
		patternMap.put("[0-9]{4}-[0-9]{2}-[0-9]{2} [0-9]{2}:[0-9]{2}:[0-9]{2}", "yyyy-MM-dd HH:mm:ss");
		patternMap.put("[0-9]{13}", "time");
		String dateStr = json.getAsString();
		if(dateStr==null||dateStr.length()<=0){return null;}
		for (Map.Entry<String, String> entry : patternMap.entrySet()) {
			String key = entry.getKey();
			String value = entry.getValue();
			Pattern compile = Pattern.compile(key);
			Matcher matcher = compile.matcher(dateStr);
			if (matcher.matches()) {
				if(value.equals("yyyy-MM-dd HH:mm:ss")){
					try {
						SimpleDateFormat format = new SimpleDateFormat(value);
						return format.parse(dateStr);
					} catch (ParseException e) {
						e.printStackTrace();
					} 
				}else if(value.equals("yyyy-MM-dd")){
					try {
						SimpleDateFormat format = new SimpleDateFormat(value);
						return format.parse(dateStr);
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}else if (value.equals("time")) {
					Date date = new Date();
					date.setTime(Long.valueOf(dateStr));
					return date;
				} else {
					SimpleDateFormat format = new SimpleDateFormat(value);
					try {
						Date date = format.parse(dateStr);
						Calendar cal = Calendar.getInstance();
						cal.setTime(date);// date 换成已经已知的Date对象
						cal.add(Calendar.HOUR_OF_DAY, +8);// after 8 hour
						return cal.getTime();
					} catch (ParseException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return null;
	}
}